package com.github.lee.core.common

import android.text.TextUtils
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.FormatStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy


object LogUtil {

    fun init(defaultTag: String, isLoggable: Boolean) {
        Logger.clearLogAdapters()
        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(true)
            .methodCount(0)
            .tag(defaultTag)
            .build()
        val logAdapter = CustomAndroidLogAdapter(formatStrategy)
        logAdapter.isLoggable = isLoggable
        Logger.addLogAdapter(logAdapter)
    }
    //===Desc:==========================================================================

    fun e(msg: String, @Nullable vararg args: Any?) {
        if (TextUtils.isEmpty(msg)) {
            w("WARN:You print message is null or length is 0")
            return
        }
        Logger.e(msg, *args)
    }

    fun e(
        @Nullable throwable: Throwable?,
        @NonNull message: String?,
        @Nullable vararg args: Any?
    ) {
        Logger.e(throwable, message!!, *args)
    }

    fun d(msg: String, vararg args: Any) {
        if (TextUtils.isEmpty(msg)) {
            w("WARN:You print message is null or length is 0")
            return
        }
        Logger.d(msg, *args)
    }

    fun i(msg: String, vararg args: Any) {
        if (TextUtils.isEmpty(msg)) {
            w("WARN:You print message is null or length is 0")
            return
        }
        Logger.i(msg, *args)
    }

    fun v(msg: String, vararg args: Any) {
        if (TextUtils.isEmpty(msg)) {
            w("WARN:You print message is null or length is 0")
            return
        }
        Logger.v(msg, *args)
    }

    fun w(msg: String, vararg args: Any) {
        if (TextUtils.isEmpty(msg)) {
            Logger.w("WARN:You print message is null or length is 0")
            return
        }
        Logger.w(msg, *args)
    }

    fun log(msg: String, priority: Int = Logger.ERROR) {
        when (priority) {
            Logger.ERROR -> e(msg)
            Logger.DEBUG -> d(msg)
            Logger.INFO -> i(msg)
            Logger.VERBOSE -> v(msg)
            Logger.WARN -> w(msg)
        }
    }

    fun log(msg: Any, priority: Int = Logger.ERROR) {
        log(msg.toString(), priority)
    }

    fun json(json: String?) {
        Logger.json(json)
    }

    fun xml(xml: String?) {
        Logger.xml(xml)
    }

}


class CustomAndroidLogAdapter(formatStrategy: FormatStrategy) : AndroidLogAdapter(formatStrategy) {
    var isLoggable: Boolean = true

    override fun isLoggable(priority: Int, tag: String?): Boolean {
        return isLoggable
    }
}